package GeoLocation::OpenStreetMapReverseGeocoder;

use strict;
use warnings;
use 5.010;

use Mojo::UserAgent;
use Utils::Constants;

sub new {
    my $class = shift;
    my $self = {};

    bless $self, $class;

    return $self;
}

sub reverse_geocode {
    my $self = shift;
    my $geolocation = shift;
    say "geo: $geolocation";
    my ($lat, $lon) = split ",", $geolocation;
    my $ua = Mojo::UserAgent->new;
    my $res = $ua->get("http://nominatim.openstreetmap.org/reverse?format=xml&lat=$lat&lon=$lon&zoom=18&addressdetails=1")->res;
    my $road = $res->dom->at('road')->text;
    my $suburb = $res->dom->at('suburb')->text;
    my $city = $res->dom->at('city')->text;
    my $state_district = $res->dom->at('state_district')->text;
    my $state = $res->dom->at('state')->text;
    my $country = $res->dom->at('country')->text;
    my $address_desc = "$road, $suburb, $city, $state_district, $state, $country";

    return defined $address_desc ? $address_desc : '';
}

1;
